import time

import pymysql


class DBUtil:

    def __init__(self, host, user, password, port):
        self.connect = pymysql.Connect(
            host=host,
            port=port,
            user=user,
            password=password,
            charset='utf8mb4',
            cursorclass=pymysql.cursors.DictCursor  # 这个参数指的数据库操作的结果是一个字典类型
        )

    def select(self, sql):
        cursor = self.connect.cursor()  # 获取一个游标对象
        cursor.execute(sql)  # 执行sql语句
        data = cursor.fetchall()  # 获取执行sql之后的结果
        self.connect.commit()  # 提交事务
        cursor.close()
        return data

    def update(self, sql):
        """
        insert、update、delete
        :param sql:
        :return:
        """
        cursor = self.connect.cursor()
        cursor.execute(sql)
        self.connect.commit()
        cursor.close()

    def close(self):
        """
        关闭数据库连接对象
        :return:
        """
        if self.connect:  # 判断connect这个不为None
            self.connect.close()


if __name__ == '__main__':
    db_util = DBUtil(host='jms.antalpha.com', user='31eb6aaa-2096-446b-a1b8-523670240761', password='mpYJD8D01kwRpPdG',port=33061)
    # for i in range(2):
    # time.sleep(2) # 等待10秒
    res = db_util.select('SELECT * FROM prime_cms.email_log ORDER BY id DESC LIMIT 4;')
    for i in res:
        print(i)
        print('===========')
    db_util.close()
